﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Web.Http.Dependencies;

namespace Seed.IoC
{
    class MefDependencyResolver : IDependencyResolver
    {
        public MefDependencyResolver(CompositionContainer container)
        {
            _container = container;
        }

        public IDependencyScope BeginScope()
        {
            return this;
        }

        public object GetService(Type serviceType)
        {
            var export = _container.GetExports(serviceType, null, string.Empty).SingleOrDefault();
            return (export != null ? export.Value : null);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            var exports = _container.GetExports(serviceType, null, string.Empty).ToList();
            return exports.Select(export => export.Value);
        }

        public void Dispose()
        {
        }

        private readonly CompositionContainer _container;
    }
}